package 线程.day3.demo5;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Teest {
    ReentrantReadWriteLock loc=new ReentrantReadWriteLock();
    synchronized void read_sync()throws Exception{
        System.out.println(Thread.currentThread().getName()+"执行方法：read_sync... ");
        System.out.println("正在读数据。。。。");
        Thread.sleep(5000);
    }

    synchronized void write_sync()throws Exception{
        System.out.println(Thread.currentThread().getName()+"执行方法：read_sync... ");
        System.out.println("正在写数据。。。。");
        Thread.sleep(5000);
    }

    void read_lock()throws Exception{
        loc.readLock().lock();//申请读锁
        System.out.println(Thread.currentThread().getName()+"执行方法read_lock");
        System.out.println("正在读数据。。。。");
        Thread.sleep(5000);
        loc.readLock().unlock();
    }
    void write_lock()throws Exception{
        loc.writeLock().lock();//申请写锁
        System.out.println(Thread.currentThread().getName()+"执行方法write_lock");
        System.out.println("正在写数据。。。。");
        Thread.sleep(5000);
        loc.writeLock().unlock();

    }

    public static void main(String[] args)throws Exception {
        Teest t=new Teest();
        //new Thread("A").start();
        new Thread("A"){
            @Override
            public void run() {
                try {
                    t.write_lock();
                } catch (Exception e) {}
            }
        }.start();
        Thread.sleep(1);
        new Thread("B"){
            @Override
            public void run() {
                try {
                    t.read_lock();
                } catch (Exception e) {}
            }
        }.start();
    }
}
